package com.qf.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.dto.ApiResult;
import com.qf.entity.User;
import com.qf.entity.request.UserRequest;
import com.qf.entity.response.UserExcel;
import com.qf.entity.response.UserImportListener;
import com.qf.enums.ApiEnum;
import com.qf.exception.GlobalException;
import com.qf.service.IUserService;
import com.qf.utils.ImageVerificationCode;
import com.qf.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chen
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关控制器")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ApiOperation("用户注册")
    @CrossOrigin
    public ApiResult register(@RequestBody UserRequest request){
        userService.register(request);
        return R.ok();
    }

    @RequestMapping(value = "/verificationCode",method = RequestMethod.POST)
    @ApiOperation("/获取验证码图片")
    @CrossOrigin
    public ApiResult verificationCode() throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageVerificationCode.output(ImageVerificationCode.getImage(),outputStream);
        //存储验证码(60秒过期)
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String text = ImageVerificationCode.getText();
        redisTemplate.opsForValue().set(uuid,text,60, TimeUnit.SECONDS);

        //转花字节数组  -》  base64
        byte[] bytes = outputStream.toByteArray();
        String encoder = Base64.getEncoder().encodeToString(bytes);
        encoder = "data:image/png;base64," + encoder;

        //构造返回值
        Map<String,Object> map = new HashMap<>();
        map.put("key",uuid);
        map.put("encoder",encoder);
        return R.ok(map);
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation("/登录")
    @CrossOrigin
    public ApiResult login(@RequestBody UserRequest request) throws IOException {
        Map<String,Object> user  = userService.login(request);
        return R.ok(user);
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiOperation("/修改用户信息")
    @CrossOrigin
    public ApiResult update(@RequestBody UserRequest request) throws IOException {
        User user = new User();
        user.setId(request.getId());
        user.setUserImg(request.getUserImg());

        User byId = userService.getById(request.getId());
        if(byId == null){
            throw new GlobalException(ApiEnum.FAIL);
        }
        if(byId.getUserStatus() == 0){
            user.setUserStatus(1);
        }else {
            user.setUserStatus(0);
        }
        userService.updateById(user);
        return R.ok();
    }

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ApiOperation("/查询用户列表")
    @CrossOrigin
    public ApiResult list(@RequestBody UserRequest request) throws IOException {
        Page<User> page = userService.findListForPage(request);
        return R.ok(page);
    }

    @RequestMapping(value = "/export",method = RequestMethod.GET)
    @ApiOperation("/导出数据")
    @CrossOrigin
    public void export( HttpServletResponse response) throws IOException {
        UserRequest request = new UserRequest();
        request.setPage(1);
        request.setSize(500);
        Page<User> page = userService.findListForPage(request);
        List<UserExcel> excelList = page.getRecords().stream().map(user -> {
            UserExcel userExcel = new UserExcel();
            BeanUtils.copyProperties(user, userExcel);
            userExcel.setId(user.getId().toString());
            return userExcel;
        }).collect(Collectors.toList());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(Charsets.UTF_8.name());
        String fileName = URLEncoder.encode("用户数据导出", Charsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(excelList);
    }

    @RequestMapping(value = "/import",method = RequestMethod.POST)
    @ApiOperation(value = "导入用户", notes = "传入excel")
    @CrossOrigin
    public ApiResult importUser(MultipartFile file, Integer isCovered) {
        //校验文件类型（是否为一个表格）
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            throw new RuntimeException("请上传文件!");
        }
        if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
            throw new RuntimeException("请上传正确的excel文件!");
        }
        //导入操作
        InputStream inputStream;
        try {
            UserImportListener importListener = new UserImportListener(userService);
            inputStream = new BufferedInputStream(file.getInputStream());
            ExcelReaderBuilder builder = EasyExcel.read(inputStream, UserExcel.class, importListener);
            builder.doReadAll();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }



}
